package com.kkd.kkdapp.activity;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.app.Dialog;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kkd.kkdapp.Environment;
import com.kkd.kkdapp.R;
import com.kkd.kkdapp.Notify.Const;
import com.kkd.kkdapp.Notify.NotifyDispatcher;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.db.CurUserModel;
import com.kkd.kkdapp.db.app.model.PdfUrlModel;
import com.kkd.kkdapp.db.app.model.User;
import com.kkd.kkdapp.http.manager.DownFileManager;
import com.kkd.kkdapp.http.manager.DownFileManager.DownLoadCallback;
import com.kkd.kkdapp.utils.FileUtils;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.MD5;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;
import com.kkd.kkdapp.view.RiseProgressBar;

public class KkdPdfWebActivity extends BaseActivity implements OnClickListener,
		OnKeyListener {

	private static final int TO_LOGIN = 1000;//
	private static final int DOWNLOAD_START = 0;
	private static final int DOWNLOAD_FINISH = 1;
	private static final int DOWNLOAD_PROGRESS = 2;
	private static final int DOWNLOAD_SIZE = 3;
	private static final int SENSOR_SHAKE = 10;

	private WebView mWebView;
	private RelativeLayout treat_top_img; // 后退
	private String rootUrl; // web的跟url
	private String pdfUrl;
	private String fileName;
	private String curUrl; // web的当前
	private TextView title_tv; // 标题
	private String titleName; // 标题名
	private ProgressBar web_increase; // 进度条
	private RiseProgressBar down_load_progress;
	private TextView progress_tv;
	private RelativeLayout share; // 分享
	private String shareUrl;
	private boolean isPost = false;
	private String desc = "[快快金融]APP,快快贷致力于打造中国最具专业性的创新型互联网金融综合借贷服务平台 ";
	private RelativeLayout happy_currency_task;
	private boolean useTitleName;
	private boolean useActiveTitle;
	private boolean isLogin = false;
	private Dialog shareFailure; // 分享失败Dialog
	private String coinMisUrl; // 快乐币任务url
	private boolean flag_onActivityResult = false;// 跳转到登录页面回来时的标记
	private RelativeLayout kkdWeb_tv_howto; // 如何获得
	private RelativeLayout happy_task_bt; // 常见问题
	private RelativeLayout down_load_rl;
	private Button down_load_bt;
	private Dialog mDialog;
	int fileLength = 0;

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case DOWNLOAD_SIZE:

				down_load_bt.setText("下载(" + fileLength / 1024 + "K)");
				break;
			case SENSOR_SHAKE:
				mWebView.loadUrl("javascript:doResult()");
				break;
			case DOWNLOAD_START:

				break;
			case DOWNLOAD_PROGRESS:
				int progress = msg.arg1;
				down_load_progress.setVisibility(View.VISIBLE);
				progress_tv.setVisibility(View.VISIBLE);
				down_load_progress.setProgress(progress);
				down_load_bt.setVisibility(View.GONE);
				progress_tv.setText("下载中(" + fileLength * progress / 102400
						+ "K/" + fileLength / 1024 + "K)");

				break;
			case DOWNLOAD_FINISH:
				down_load_bt.setVisibility(View.VISIBLE);
				progress_tv.setVisibility(View.GONE);
				down_load_bt.setText("已下载，查看下载位置");
				down_load_progress.setProgress(100);
				String path = msg.obj.toString();
				Toast.makeText(KkdPdfWebActivity.this, "已下载到：" + path,
						Toast.LENGTH_LONG).show();
				PdfUrlModel.insert(MD5.Md5File(path), rootUrl);
				PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat(
						"alpha", 1f, 0f);
				ObjectAnimator animator = ObjectAnimator
						.ofPropertyValuesHolder(down_load_progress, alpha);
				animator.setDuration(1000).start();
				animator.addListener(new AnimatorListener() {

					@Override
					public void onAnimationStart(Animator animation) {
					}

					@Override
					public void onAnimationRepeat(Animator animation) {
					}

					@Override
					public void onAnimationEnd(Animator animation) {
						down_load_progress.setVisibility(View.GONE);
					}

					@Override
					public void onAnimationCancel(Animator animation) {
					}
				});
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pdf_web);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
						| WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
		vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
		Intent intent = getIntent();

		rootUrl = intent.getStringExtra("url");
		pdfUrl = intent.getStringExtra("pdfUrl");
		fileName = intent.getStringExtra("fileName");
		isPost = rootUrl.indexOf("isPost") > 0;
		isLogin = rootUrl.indexOf("isLogin") > 0;
		curUrl = rootUrl;
		titleName = intent.getStringExtra("titleName");
		shareUrl = intent.getStringExtra("shareUrl");
		desc = intent.getStringExtra("desc");
		useTitleName = intent.getBooleanExtra("useTitleName", false);
		useActiveTitle = intent.getBooleanExtra("useActiveTitle", false);
		mWebView = (WebView) this.findViewById(R.id.treaty_web);
		treat_top_img = (RelativeLayout) this.findViewById(R.id.treat_top_img);
		title_tv = (TextView) this.findViewById(R.id.treat_top_tv);
		web_increase = (ProgressBar) this.findViewById(R.id.web_increase);
		down_load_progress = (RiseProgressBar) findViewById(R.id.down_load_progress);
		progress_tv = (TextView) findViewById(R.id.progress_tv);
		share = (RelativeLayout) this.findViewById(R.id.share);
		happy_currency_task = (RelativeLayout) findViewById(R.id.happy_currency_task);
		if ("".equals(shareUrl) || shareUrl == null) {
			share.setVisibility(View.GONE);
		} else {
			share.setVisibility(View.VISIBLE);
		}
		treat_top_img.setOnClickListener(this);
		share.setOnClickListener(this);
		happy_currency_task.setOnClickListener(this);
		mWebView.setOnKeyListener(this);
		initWeb();
		coinMisUrl = intent.getStringExtra("coinMisUrl");
		LogUtil.e("TAG", "coinMisUrl--->" + coinMisUrl);
		kkdWeb_tv_howto = (RelativeLayout) this
				.findViewById(R.id.kkdWeb_tv_howto);
		kkdWeb_tv_howto.setOnClickListener(this);
		happy_task_bt = (RelativeLayout) this.findViewById(R.id.happy_task_bt);
		happy_task_bt.setOnClickListener(this);
		down_load_rl = (RelativeLayout) this.findViewById(R.id.down_load_rl);
		down_load_bt = (Button) findViewById(R.id.down_load_bt);
		down_load_bt.setOnClickListener(this);
		if (TextUtils.isEmpty(pdfUrl)) {
			down_load_rl.setVisibility(View.GONE);
		} else {
			down_load_rl.setVisibility(View.VISIBLE);
			File file = new File(FileUtils.getKKDRootPath() + "pdf/" + fileName);
			if (file.exists()) {
				down_load_bt.setText("已下载，查看下载位置");
			} else {
				Thread pdfThread = new Thread(new Runnable() {

					@Override
					public void run() {
						try {
							URL downPdfUrl = new URL(pdfUrl);
							HttpURLConnection urlcon = (HttpURLConnection) downPdfUrl
									.openConnection();
							fileLength = urlcon.getContentLength();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						mHandler.sendEmptyMessage(DOWNLOAD_SIZE);
					}
				});
				pdfThread.start();
			}

		}

	}

	/**
	 * initWeb:(初始化webview 设置).
	 * 
	 * @author askzhao
	 */
	private void initWeb() {
		WebSettings webSettings = mWebView.getSettings();
		// 设置WebView属性，能够执行Javascript脚本
		webSettings.setJavaScriptEnabled(true);
		mWebView.getSettings().setDefaultTextEncodingName("utf-8");
		// 设置可以访问文件
		webSettings.setAllowFileAccess(true);
		// 设置支持缩放
		webSettings.setBuiltInZoomControls(true);
		webSettings.setDomStorageEnabled(true);
		webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
		// 设置Web视图
		mWebView.setWebViewClient(new WebViewClient() {
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				if (url.startsWith("tel:")) {
					Intent intent = new Intent(Intent.ACTION_VIEW, Uri
							.parse(url));
					startActivity(intent);
				} else if (url.startsWith("http:") || url.startsWith("https:")) {
					view.loadUrl(url);
				}
				return true;
			}

			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				super.onReceivedError(view, errorCode, description, failingUrl);
				// mWebView.loadUrl("file:///android_asset/rate.html");
			};

			public void onReceivedSslError(WebView view,
					SslErrorHandler handler, SslError error) {
				handler.proceed();
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				if (flag_onActivityResult) {
					flag_onActivityResult = false;
					mWebView.clearHistory();
				}
				mWebView.loadUrl("javascript:(function() { var videos = document.getElementsByTagName('video'); for(var i=0;i<videos.length;i++){videos[i].play();}})()");
				curUrl = url;
				reSetSensorManager();
				String title = view.getTitle();
				if (useTitleName) {
					if (titleName != null) {
						title_tv.setText(titleName);
					}
				} else {
					title_tv.setText(title);
				}
				if (useActiveTitle) {
					title_tv.setText("活动公告");
				}
				if ("快乐商城".equals(title)) {
					if (TextUtils.isEmpty(coinMisUrl)) {
						happy_currency_task.setVisibility(View.GONE);
						kkdWeb_tv_howto.setVisibility(View.VISIBLE);
					} else {
						happy_currency_task.setVisibility(View.VISIBLE);
						kkdWeb_tv_howto.setVisibility(View.GONE);
					}
				} else {
					happy_currency_task.setVisibility(View.GONE);
					kkdWeb_tv_howto.setVisibility(View.GONE);
				}
				if ("快乐币任务".equals(title)) {
					happy_task_bt.setVisibility(View.VISIBLE);
				} else {
					happy_task_bt.setVisibility(View.GONE);
				}

			}
		});
		mWebView.setWebChromeClient(new WebChromeClient() {

			@Override
			public boolean onJsAlert(WebView view, String url, String message,
					JsResult result) {
				return super.onJsAlert(view, url, message, result);
			}

			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				super.onProgressChanged(view, newProgress);
				web_increase.setVisibility(View.VISIBLE);
				web_increase.setProgress(newProgress);
				if (newProgress == 100) {
					PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat(
							"alpha", 1f, 0f);
					ObjectAnimator animator = ObjectAnimator
							.ofPropertyValuesHolder(web_increase, alpha);
					animator.setDuration(1000).start();
					animator.addListener(new AnimatorListener() {

						@Override
						public void onAnimationStart(Animator animation) {
						}

						@Override
						public void onAnimationRepeat(Animator animation) {
						}

						@Override
						public void onAnimationEnd(Animator animation) {
							web_increase.setVisibility(View.GONE);
						}

						@Override
						public void onAnimationCancel(Animator animation) {
						}
					});
				}
			}

			@Override
			public void onReceivedTitle(WebView view, String title) {
				super.onReceivedTitle(view, title);
			}
		});

		mWebView.addJavascriptInterface(new JsInteration(), "KKD_Control");
	}

	@Override
	protected void onResume() {
		super.onResume();
		reSetSensorManager();
		// if (curUrl.equals(rootUrl))
		// loadweb();
		if (!rootUrl.contains("&customerId=")) {
			String curUrl_begin;
			if (curUrl.contains("&customerId=")
					&& curUrl.indexOf("&customerId=") > 0) {
				curUrl_begin = curUrl.substring(0,
						curUrl.indexOf("&customerId="));
			} else {
				curUrl_begin = curUrl;
			}
			if (curUrl_begin.equals(rootUrl) && !flag_onActivityResult)
				loadweb();
		} else {
			if (curUrl.equals(rootUrl) && !flag_onActivityResult)
				loadweb();
		}
		mWebView.onResume();
	}

	public void loadweb() {

		mWebView.clearHistory();

		// 加载需要显示的网页
		if (rootUrl.indexOf("isLogin") >= 0
				&& PreferenceUtils.getLogin(this) != 0) {

			Intent intent = new Intent(KkdPdfWebActivity.this,
					LoginActivity.class);
			startActivityForResult(intent, TO_LOGIN);

		} else {
			if (isPost) {
				User user = CurUserModel.getCurUser();
				String postdata = "";
				if (user != null) {
					postdata = "customerId=" + user.customerId + "&token="
							+ user.token + "&channel=Android&version="
							+ SystemUtils.getVersionName(this);
				} else {
					postdata = "customerId=&token=&channel=Android&version="
							+ SystemUtils.getVersionName(this);
				}
				if ("快乐币任务提醒".equals(titleName))
					postdata = postdata + "&name=task";
				mWebView.loadUrl(rootUrl + "&" + postdata);
			} else {
				mWebView.loadUrl(rootUrl);

			}
		}
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.treat_top_img: // 后退
			if (mWebView.canGoBack()) {
				mWebView.goBack();
			} else {
				finish();
			}
			break;
		case R.id.down_load_bt:
			if (down_load_bt.getText().toString().equals("已下载，查看下载位置")) {
				Intent intent = new Intent(KkdPdfWebActivity.this,
						FileManagerActivity.class);
				intent.putExtra("rootPath", FileUtils.getKKDRootPath() + "pdf/");
				intent.putExtra("fileName", fileName);
				startActivity(intent);
			} else {
				downLoadFile(pdfUrl, "pdf");
			}

			break;
		case R.id.happy_currency_task: // 快乐币任务
			Intent intent = new Intent(KkdPdfWebActivity.this,
					KkdPdfWebActivity.class);
			intent.putExtra("url", coinMisUrl);
			startActivity(intent);
			finish();
			break;

		case R.id.share:
			String tile = "快快贷理财";
			String tip = "[快快金融]APP,快快贷致力于打造中国最具专业性的创新型互联网金融综合借贷服务平台 ";
			if (!TextUtils.isEmpty(titleName)) {
				tile = titleName;
			}
			if (!TextUtils.isEmpty(desc)) {
				tip = desc;

			}
			// 加载需要显示的网页
			if (isLogin) {
				if (PreferenceUtils.getInstance().getLogin(
						KkdPdfWebActivity.this) == 0) { // 登录
					toShareURL(KkdPdfWebActivity.this, shareUrl, tile, tip,
							R.drawable.share_kkdai_logo);
				} else if (PreferenceUtils.getInstance().getLogin(
						KkdPdfWebActivity.this) != 0) { // 未登录
					Intent mIntent = new Intent(KkdPdfWebActivity.this,
							LoginActivity.class);
					startActivityForResult(mIntent, TO_LOGIN);
				}
			} else {
				toShareURL(KkdPdfWebActivity.this, shareUrl, tile, tip,
						R.drawable.share_kkdai_logo);
			}

			break;
		case R.id.kkdWeb_tv_howto: // 如何获得
			intent = new Intent(KkdPdfWebActivity.this,
					HowToHappyCoinActivity.class);
			startActivity(intent);
			break;
		case R.id.happy_task_bt: // 快乐币任务常见问题
			intent = new Intent(KkdPdfWebActivity.this, KkdPdfWebActivity.class);
			intent.putExtra("url", Environment.getH5Url()
					+ "/appIconques.html?channel=Android");
			startActivity(intent);
			break;
		}
	}

	@Override
	protected void onPause() {

		super.onPause();
		mWebView.onPause();
		if (sensorManager != null) {// 取消监听器
			sensorManager.unregisterListener(sensorEventListener);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		web_increase.setProgress(0);
		if (mediaPlayer != null) {
			mediaPlayer.stop();
			mediaPlayer.release();
		}
		if (shareFailure != null) {
			shareFailure.cancel();
			shareFailure = null;
		}
		shareResult = -1;
		PreferenceUtils.getInstance().clearSharePrefernces(
				KkdPdfWebActivity.this);
	}

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN) {
			switch (v.getId()) {
			case R.id.treaty_web:
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					if (mWebView.canGoBack()) {
						mWebView.goBack();
					} else {
						finish();
					}
					return true;
				}
				break;
			}
		}

		return false;
	}

	public class JsInteration {

		@JavascriptInterface
		public void toastMessage(String message) {
			Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG)
					.show();
		}

		@JavascriptInterface
		public void gotoLogin() {
			Intent intent = new Intent(KkdPdfWebActivity.this,
					LoginActivity.class);
			startActivityForResult(intent, TO_LOGIN);
		}

		@JavascriptInterface
		public void isOpenShakeListener(boolean is) {
			isOpenShakeListener = is;
		}

		@JavascriptInterface
		public void gotoMyDiscountCoupon() {
			Intent intent = new Intent(KkdPdfWebActivity.this,
					MyDiscountCouponActivity.class);
			startActivity(intent);
		}

		@JavascriptInterface
		public void jsCopy(String content) {
			ClipboardManager cmb = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
			cmb.setText(content.trim());
		}

		@JavascriptInterface
		public void jumpto(String pkg, String cls) {

			if (cls.indexOf("LoginActivity") > 0) {
				gotoLogin();
			} else {
				ComponentName componet = new ComponentName(pkg, cls);
				Intent intent = new Intent();
				intent.setComponent(componet);
				if (cls.indexOf("HomeActivity") > 0) {
					intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				} else {
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				}
				if (cls.indexOf("RechargeActivity") > 0
						&& (PreferenceUtils.getInstance().getAutonym(
								KkdPdfWebActivity.this) == 0 || PreferenceUtils
								.getInstance().getBoundBankCard(
										KkdPdfWebActivity.this) == 0)) {
					// 跳转到充值页需要先完成投资前准备
					Intent intent_toForTender = new Intent(
							KkdPdfWebActivity.this, ForTenderActivity.class);
					intent_toForTender.putExtra("enterTypeFlag", 3);
					startActivity(intent_toForTender);
				} else {
					startActivity(intent);
				}
			}

		}

		@JavascriptInterface
		public void jumptoHome(int toActivity) {
			Intent intent = new Intent(KkdPdfWebActivity.this,
					HomeActivity.class);
			intent.putExtra("toActivity", toActivity);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}

		@JavascriptInterface
		public void jumptoWithIntent(String pkg, String cls) {

			ComponentName componet = new ComponentName(pkg, cls);
			Intent intent = new Intent();
			intent.setComponent(componet);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		}

		@JavascriptInterface
		public boolean isLogin() {
			return PreferenceUtils.getInstance().getLogin(
					KkdPdfWebActivity.this) == 0;
		}

		@JavascriptInterface
		public void toShare(String inviteFriendUrl, String title,
				String content, String logo, String entrance) {
			PreferenceUtils.getInstance().setH5Parameter(
					KkdPdfWebActivity.this, inviteFriendUrl, title, content,
					logo);
			PreferenceUtils.getInstance().setH5Entrance(KkdPdfWebActivity.this,
					entrance);
			toShareURL(KkdPdfWebActivity.this, inviteFriendUrl, title, content,
					logo);

		}

		@JavascriptInterface
		public void playMoneytree() {
			mediaPlayer = MediaPlayer.create(KkdPdfWebActivity.this,
					R.raw.moneytree);
			if (mediaPlayer.isPlaying()) {
				mediaPlayer.reset();
			}
			mediaPlayer.setLooping(false);
			try {
				mediaPlayer.prepare();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			mediaPlayer.start();
		}

		@JavascriptInterface
		public void toSign() {
			Intent intent = new Intent(KkdPdfWebActivity.this,
					HomeActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			NotifyDispatcher.getInstance().sendNotify("",
					Const.NOTIFY_HOME_SIGN);
			finish();
		}

		@JavascriptInterface
		public void toTender(String group_name) {
			Intent intent = new Intent(KkdPdfWebActivity.this,
					SelectedBidActivity.class);
			intent.putExtra("group_name", group_name);
			startActivity(intent);
			finish();
		}

		@JavascriptInterface
		public String getNetTypeName() {
			return SystemUtils.getNetTypeName();
		}

		@JavascriptInterface
		public void downLoadFile(final String fileUrl, final String fileType) {
			downLoadFile(fileUrl, fileType);
		}
	}

	public void downLoadFile(final String fileUrl, final String fileType) {

		DownFileManager.getInstance().downloadFile(
				FileUtils.getKKDRootPath() + fileType + "/", fileUrl, fileName,
				fileType, new DownLoadCallback() {

					@Override
					public void onProgress(int progress) {
						Message msg = new Message();
						msg.what = DOWNLOAD_PROGRESS;
						msg.arg1 = progress;
						mHandler.sendMessage(msg);
					}

					@Override
					public void onFinish() {
						Message msg = new Message();
						msg.what = DOWNLOAD_FINISH;
						msg.obj = FileUtils.getKKDRootPath() + fileType + "/"
								+ fileName;
						mHandler.sendMessage(msg);
					}

					@Override
					public void onDownLoading() {
						// TODO Auto-generated method stub

					}

					@Override
					public void onCancle() {
						// TODO Auto-generated method stub

					}
				});
	}

	private MediaPlayer mediaPlayer;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == TO_LOGIN) {
			if (resultCode == LoginActivity.LOGIN_SUCCESS) {
				flag_onActivityResult = true;
				loadweb();
			} else {
				if (TextUtils.isEmpty(mWebView.getUrl())) {
					finish();
				}
			}
		}

	}

	private SensorManager sensorManager;
	private Vibrator vibrator;

	private long lastShakeTime = 0;
	private boolean isOpenShakeListener = true;
	/**
	 * 重力感应监听
	 */
	private SensorEventListener sensorEventListener = new SensorEventListener() {
		@Override
		public void onSensorChanged(SensorEvent event) {
			// 传感器信息改变时执行该方法
			float[] values = event.values;
			float x = values[0]; // x轴方向的重力加速度，向右为正
			float y = values[1]; // y轴方向的重力加速度，向前为正
			float z = values[2]; // z轴方向的重力加速度，向上为正
			// 一般在这三个方向的重力加速度达到40就达到了摇晃手机的状态。
			int medumValue = 13;// 三星 i9250怎么晃都不会超过20，没办法，只设置19了
			if (isOpenShakeListener
					&& (Math.abs(x) + Math.abs(y) + Math.abs(z)) > 37
					&& (System.currentTimeMillis() - lastShakeTime) > 1000) {
				lastShakeTime = System.currentTimeMillis();
				vibrator.vibrate(200);
				Message msg = new Message();
				msg.what = SENSOR_SHAKE;
				mHandler.sendMessage(msg);
			}
		}

		@Override
		public void onAccuracyChanged(Sensor sensor, int accuracy) {
		}
	};

	private void reSetSensorManager() {
		if (curUrl.contains("moneytree") && sensorManager != null) {// 注册监听器
			sensorManager.registerListener(sensorEventListener,
					sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
					SensorManager.SENSOR_DELAY_NORMAL);
			// 第一个参数是Listener，第二个参数是所得传感器类型，第三个参数值获取传感器信息的频率
		} else {
			if (sensorManager != null) {// 取消监听器
				sensorManager.unregisterListener(sensorEventListener);
			}
		}
	}

}